/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.au.uq.datamining.web.servlet;

import edu.au.uq.datamining.entity.AdditionalInfo;
import edu.au.uq.datamining.entity.AdditionalInfoPK;
import edu.au.uq.datamining.entity.BasicInfo;
import edu.au.uq.datamining.entity.BasicInfoPK;
import edu.au.uq.datamining.entity.Datamart;
import edu.au.uq.datamining.entity.Tpersonaid;
import edu.au.uq.datamining.session.ManagerRemote;
import edu.au.uq.datamining.tree.Tree;
import edu.au.uq.datamining.util.DatamartInstance;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

import weka.core.Attribute;
import weka.core.FastVector;

import weka.core.Instance;
import weka.core.Instances;

/**
 *
 * @author oracle
 */
@WebServlet(name = "GeneralServlet", urlPatterns = {"/GeneralServlet"})
public class GeneralServlet extends HttpServlet {

    @EJB
    private ManagerRemote manager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String lastName = request.getParameter("lastName").toUpperCase();
            String secondLastName = request.getParameter("secondLastName").toUpperCase();
            String firstName = request.getParameter("firstName").toUpperCase();
            String middleName = request.getParameter("middleName").toUpperCase();
            String gender = request.getParameter("gender").toUpperCase();
            String status = request.getParameter("status").toUpperCase();
            String house = request.getParameter("house").toUpperCase();
            String nationality = request.getParameter("nationality").toUpperCase();
            BigDecimal income = new BigDecimal(request.getParameter("income"));
            String child = request.getParameter("child");
            String education = request.getParameter("education").toUpperCase();
            String government = request.getParameter("government").toUpperCase();
            String loan = "YES";

            Integer nextPerson = manager.getMaxPerson();
            Tpersonaid person = new Tpersonaid();
            person.setCpersona(nextPerson);
            //manager.savePerson(person);

            BasicInfoPK basicInfoPk = new BasicInfoPK(nextPerson, new Date());
            AdditionalInfoPK additionalInfoPK = new AdditionalInfoPK(nextPerson, new Date());

            BasicInfo basicInfo = new BasicInfo(basicInfoPk, lastName, secondLastName, firstName, middleName, gender, new Short(status), house);
            AdditionalInfo additionalInfo = new AdditionalInfo(additionalInfoPK, nationality, income, new Short(child), new Short(education), government, loan);
            //manager.saveData(additionalInfo, basicInfo);
            double val=-1;
            Tree tree = new Tree();
            tree.setInstances(generateInstances(manager.getAllData()));
            Instance newInstance=generateInstance(gender,status,house,nationality,income,child,education,government,loan);
            val=tree.getJ48(newInstance);
            tree.comprobar();
            RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
            if(val==0d){
                request.setAttribute("message", "The client can apply for a Loan");
            }else{
                request.setAttribute("message", "The client can't apply for a Loan");
            }
            rd.forward(request, response);
        } finally {
            out.close();
        }
    }

    private Instances generateInstances(List<Datamart> list) {
        FastVector fvWekaAttributes = DatamartInstance.createAttributes();
        Instances instances = new Instances("Rel", fvWekaAttributes, 9);
        instances.setClassIndex(instances.numAttributes() - 1);
        for (Datamart datamart : list) {
            Instance iExample = new Instance(9);
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(0), datamart.getGender());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(1), datamart.getMaritalstatus());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(2), datamart.getHousetype());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(3), datamart.getNationality());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(4), datamart.getIncome());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(5), String.valueOf(datamart.getChild().intValue()));
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(6), datamart.getEducation());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(7), datamart.getWorkforgovernment());
            iExample.setValue((Attribute) fvWekaAttributes.elementAt(8), datamart.getLoan());
            instances.add(iExample);
        }
        return instances;
    }

    private Instance generateInstance(String gender, String status, String house, String nationality, BigDecimal income, String child, String education, String government, String loan) {

        if (education.equals("99")) {
            education = "DESCONOCIDA";
        } else if (education.equals("0")) {
            education = "NINGUNA";
        } else if (education.equals("1")) {
            education = "PRIMARIA";
        } else if (education.equals("2")) {
            education = "SECUNDARIA";
        } else if (education.equals("3")) {
            education = "TECNICA";
        } else if (education.equals("4")) {
            education = "UNIVERSITARIO";
        } else if (education.equals("5")) {
            education = "PROFESIONAL";
        } else if (education.equals("6")) {
            education = "ESPECIALIZACION";
        } else {
            education = "TECNICA";
        }

        if (status.equals("1")) {
            status = "SOLTERO";
        } else if (status.equals("2")) {
            status = "CASADO";
        } else if (status.equals("3")) {
            status = "DIVORCIADO";
        } else if (status.equals("4")) {
            status = "VIUDO";
        } else if (status.equals("5")) {
            status = "UNIONLIBRE";
        } else if (status.equals("6")) {
            status = "CONCUBINATO";
        } else if (status.equals("7")) {
            status = "CASADOSEPARBIENES";
        } else if (status.equals("9")) {
            status = "DESCONOCIDO";
        } else {
            status = "SOLTERO";
        }

        String rangeIncome="";

        if(income.doubleValue()>=0 && income.doubleValue()<10000){
        rangeIncome="0-10000";}else if(income.doubleValue()>=10000 && income.doubleValue()<40000){
        rangeIncome="10000-40000";}else if(income.doubleValue()>=40000 && income.doubleValue()<70000){
        rangeIncome="40000-70000";}else{
        rangeIncome="70000";}


        FastVector fvWekaAttributes = DatamartInstance.createAttributes();
        Instances instances = new Instances("Rel", fvWekaAttributes, 9);
        instances.setClassIndex(instances.numAttributes() - 1);
        
        System.out.println(gender+";"+status+";"+house+";"+nationality+";"+rangeIncome+";"+child+";"+education+";"+government+";"+loan);

        Instance iExample = new Instance(9);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(0), gender);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(1), status);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(2), house);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(3), nationality);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(4), rangeIncome);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(5), child);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(6), education);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(7), government);
        iExample.setValue((Attribute) fvWekaAttributes.elementAt(8), loan);
        instances.add(iExample);

        return instances.firstInstance();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
